package com.darrenchan.leetcode;

/**
 * @Desc
 * @Author chenchi03
 * @CreateTime 2020-04-23 10:53
 */
public class QLint144 {
    public void rerange(int[] A) {
        if(A == null || A.length == 0) {
            return;
        }

        int i = 0, j = A.length - 1;
        while (i <= j) {
            while (i <= j && A[i] < 0) {
                i++;
            }

            while (i <= j && A[j] > 0) {
                j--;
            }

            if(i <= j) {
                int temp = A[i];
                A[i] = A[j];
                A[j] = temp;

                i++;
                j--;
            }
        }

        int negativeNum = i;
        int positiveNum = A.length - negativeNum;
        //交换前后区间
        if(negativeNum * 2 < A.length) {
            i = 0;
            j = A.length - 1;
            while (i < j) {
                int temp = A[i];
                A[i] = A[j];
                A[j] = temp;

                i++;
                j--;
            }
        }

        //这样保证前面的数大于等于后面的数
        if(negativeNum == positiveNum) {
            swap(A, 1, A.length - 2);
        } else {
            swap(A, 1, A.length - 1);
        }
    }

    private void swap(int[] A, int i, int j) {
        while (i < j) {
            int temp = A[i];
            A[i] = A[j];
            A[j] = temp;

            i += 2;
            j -= 2;
        }
    }
}
